package upload

import (
	"context"
	"fmt"
	"gitee.com/bobo-rs/creative-framework/pkg/ifile"
	"gitee.com/bobo-rs/creative-services/framework/model"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
)

// ProcessLocalUpload 处理本地上传文件
func (u *sUpload) ProcessLocalUpload(ctx context.Context, in model.UploadFileInput, item *model.UploadAttachmentItem) (err error) {
	// 读取配置
	rawConfig := model.UploadConfigLocalItem{}
	if err = gconv.Struct(RawConfig.Config, &rawConfig); err != nil {
		return err
	}

	// 获取文件真名
	realName := in.File.Filename
	if in.Name != "" {
		in.File.Filename = in.Name + gfile.Ext(realName)
		// 指定文件名
		in.RandomName = false
	}

	// 生成文件名
	dateDirName := gtime.Now().Format("Ymd")
	fileName, err := in.File.Save(gfile.Join(rawConfig.Root, rawConfig.Path, dateDirName), in.RandomName)
	if err != nil {
		return err
	}

	// 记录到数据表
	pathUrl := ifile.SlashUploadPath(
		fmt.Sprintf(`%s/%s/%s`, rawConfig.Path, dateDirName, fileName),
	)
	item.StorageType = RawConfig.StorageType
	item.Name = fileName
	item.AttType = in.File.Header.Get(`Content-Type`)
	item.AttPath = pathUrl
	item.AttUrl = pathUrl
	item.AttSize = int(in.File.Size)
	item.RealName = gfile.Name(realName)

	// 获取图片高宽度
	w, h, _ := ifile.New(rawConfig.Root + item.AttPath).ImageWH()
	item.Width = uint(w)
	item.Height = uint(h)

	return
}
